#!/usr/bin/env python
from urllib import urlopen as uo
from urllib import urlencode as ue
import sys
try:
    import lxml.etree as etree
except:
    sys.exit("You must have the lxml python module to use this utility")

parser = etree.HTMLParser()
from optparse import OptionParser

oparser = OptionParser()
oparser.add_option("-i", "--input", dest="inputform", default=False, action="store_true",
                  help="Output resulting integran in 'input' form" )
oparser.add_option("-p", "--pretty",
                  dest="prettyform", action="store_true",default=False,
                  help="Output resulting integran in a pretty form")
oparser.add_option("-v", "--verbose",
                  dest="pretty", action="store_true",default=False,
                  help="Output resulting integran in a pretty form")

def getintegral(function):
    d = {"expr": function}
    data = uo("http://integrals.wolfram.com/index.jsp?",ue(d))
    root = etree.parse(data,parser).getroot()
    #input_form = root.xpath('/html/body/div/div[3]/div[3]/div[3]/pre')[0].text
    input_form = [a for a in root.xpath('/html/body/div/div[3]/div[3]/div[2]/p')[0].itertext()][2]
    pretty_form = root.xpath('/html/body/div/div[3]/div[3]/div[3]/pre[2]')[0].text
    return input_form,pretty_form


if __name__ == "__main__":
    (options, args) = oparser.parse_args()    
    if len(args) != 1: sys.exit("Please supply only one function and encapsulate it with parenthesis")
    input_form,pretty_form = getintegral(args[0])
    if not options.prettyform and not options.inputform: options.inputform= True
    if options.inputform:
        print "%s" % (input_form)
    if options.prettyform :
        print "%s" % (pretty_form)


    
